﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows;
using System.Globalization;
using System.IO;

namespace ResourceViewerExtension.Common
{
    public static class ShortenPathHelper
    {
        private static double MeasureString(string str)
        {
            FormattedText formattedText = new FormattedText(
                str,
                CultureInfo.GetCultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface("Tahoma"),
                11,
                Brushes.Black);

            return formattedText.WidthIncludingTrailingWhitespace;

        }

        public static string ShortenPath(string path, double desiredMexWidth)
        {
            string formattedPath = "";
            if (MeasureString(path) < desiredMexWidth)
            {
                formattedPath = path;
            }
            else
            {

                string root = Path.GetPathRoot(path);
                string[] elements = path.Substring(root.Length).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                string fileName = elements[elements.Length - 1];

                formattedPath = String.Format(@"{0}...\{1}", root, fileName);

                double formattedPathWidth = MeasureString(formattedPath);

                for (int i = elements.Length - 2; i > -1; i--)
                {
                    string nextString = string.Format(@"\{0}", elements[i]);
                    double nextStringWidth = MeasureString(nextString);
                    if (formattedPathWidth + nextStringWidth < desiredMexWidth)
                    {
                        formattedPath = formattedPath.Insert(6, nextString);
                        formattedPathWidth = MeasureString(formattedPath);
                    }
                    else
                        break;
                }
            }

            return formattedPath;
        }
    }
}
